package com.tjtt.tdm.visual.dao.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.springframework.context.ApplicationContext;

import com.tjtt.tdm.base.HibernateEntityDAO;
import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.visual.bean.VisualInfo;
import com.tjtt.tdm.visual.dao.VisualDao;

public class VisualDaoImpl extends HibernateEntityDAO<VisualInfo> implements VisualDao{
	private static final Log log = LogFactory.getLog(VisualDao.class);
	protected void initDao() {
		// do nothing
	}

	public String save(VisualInfo transientInstance) {
		log.debug("saving VisualInfo instance");
		try {
			String id = "";
			id = getHibernateTemplate().save(transientInstance).toString();
			log.debug("save successful");
			return id;
		} catch (RuntimeException re) {
			log.error("save failed", re);
			return "";
		}
	}
	
	public String saveobject(Object transientInstance) {
		log.debug("saving VisualInfo instance");
		try {
			String id = "";
			id = getHibernateTemplate().save(transientInstance).toString();
			log.debug("save successful");
			return id;
		} catch (RuntimeException re) {
			log.error("save failed", re);
			return "";
		}
	}

	public void delete(VisualInfo persistentInstance) {
		log.debug("deleting VisualInfo instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public VisualInfo findById(java.lang.Long id) {
		log.debug("getting VisualInfo instance with id: " + id);
		try {
			VisualInfo instance = (VisualInfo) getHibernateTemplate().get(
					"com.tjtt.tdm.visual.bean.VisualInfo", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(VisualInfo instance) {
		log.debug("finding VisualInfo instance by example");
		try {
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding VisualInfo instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from VisualInfo as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	
	public List findAllByWhere(String where) {
		log.debug("finding all VisualInfo instances");
		try {
			String queryString = "from VisualInfo where "+where;
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public List findAll() {
		log.debug("finding all VisualInfo instances");
		try {
			String queryString = "from VisualInfo";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public List findAllBySql(String sql,int start,int rows)
	{
		log.debug("finding all VisualInfo instances");
		try {
			Query query = getSession().createSQLQuery(sql);
			query.setFirstResult(start);
			query.setMaxResults(rows);
			List list = query.list();
			return list;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public List findAllBySql(String sql)
	{
		log.debug("finding all VisualInfo instances");
		try {
			Query query = getSession().createSQLQuery(sql);
			List list = query.list();
			return list;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public void executeBySql(String sql)
	{
		log.debug("finding all VisualInfo instances");
		try {
			getSession().createSQLQuery(sql).executeUpdate();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public VisualInfo merge(VisualInfo detachedInstance) {
		log.debug("merging VisualInfo instance");
		try {
			VisualInfo result = (VisualInfo) getHibernateTemplate().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(VisualInfo instance) {
		log.debug("attaching dirty VisualInfo instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(VisualInfo instance) {
		log.debug("attaching clean VisualInfo instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	
	public Long getMaxId()
	{
		log.debug("获得最大的ID值");
		try {
			Query query = getSession().createSQLQuery("select id from flow_flowtype order by id desc");
			List list = query.list();
			if (list.size()==0)
			{
				return Long.parseLong("0")+1;
			}
			else
			{
				String maxID = list.get(0).toString();
				return Long.parseLong(maxID)+1;
			}
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	
	public void delVisualInfoById(String id)
	{
		try {
			getSession().createSQLQuery("delete from sys_visualinfo where id="+id).executeUpdate();
		} catch (RuntimeException re) {
			log.error("del by id", re);
			throw re;
		}
	}
	
	public void update(VisualInfo instance) {
		log.debug("update dirty VisualInfo instance");
		try {
			getHibernateTemplate().update(instance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}
	

	public static VisualDao getFromApplicationContext(ApplicationContext ctx) {
		return (VisualDao) ctx.getBean("VisualDao");
	}

	
	public PageResult GetVisualList(Map<String, String> filterMap) {
		StringBuffer queryString = new StringBuffer();
		StringBuffer queryCountString = new StringBuffer();
		queryString.append("select id,VISUALNAME,PICADDRESS,REMARK,PARENTID from sys_visualinfo where 1=1 and type!=-2 ");
		queryCountString.append(" select count(*) from sys_visualinfo where 1=1 and type!=-2 ");		
		if (filterMap != null && !filterMap.isEmpty()) {	
			if(null!=filterMap.get("visualId")&&!"".equals(filterMap.get("visualId"))&&(null==filterMap.get("notin")||"".equals(filterMap.get("notin")))){
				queryString.append("and id=").append(filterMap.get("visualId"));
				queryCountString.append("and id=").append(filterMap.get("visualId"));
			}

			if(null!=filterMap.get("type")&&!"".equals(filterMap.get("type"))){
				queryString.append(" and type=").append(filterMap.get("type"));
				queryCountString.append(" and type=").append(filterMap.get("type"));
			}
			if(null!=filterMap.get("pId")&&!"".equals(filterMap.get("pId"))){
				queryString.append(" and parentid=").append(filterMap.get("pId"));
				queryCountString.append(" and parentid=").append(filterMap.get("pId"));
			}
			if(null!=filterMap.get("notin")&&!"".equals(filterMap.get("notin"))){
				queryString.append(" and id <> ").append(filterMap.get("visualId"));
				queryCountString.append(" and id <> ").append(filterMap.get("visualId"));
			}
			String sidx = (String) filterMap.get("sidx");
			String sord = (String) filterMap.get("sord");
			queryString.append(" order by " + sidx + " " + sord + " ");
			if(null!=filterMap.get("childId")&&!"".equals(filterMap.get("childId"))){
				queryString.delete(0, queryString.length());
				queryCountString.delete(0, queryCountString.length());
				queryString.append("select t.id,t.VISUALNAME,t.PICADDRESS,t.REMARK,t.PARENTID from sys_visualinfo t start with t.id = (select min(t.id)" +
						"from sys_visualinfo t start with t.id = '"+filterMap.get("childId")+"' connect by prior t.parentid = t.id " +
						"and t.type <> -2) connect by prior  t.id = t.parentid  and t.type <> -2 ");
				queryCountString.append(" select count(*) from sys_visualinfo t start with t.id = (select min(t.id)" +
						"from sys_visualinfo t start with t.id = '"+filterMap.get("childId")+"' connect by prior  t.parentid = t.id " +
						"and t.type <> -2) connect by prior  t.id = t.parentid  and t.type <> -2  ");
			}


		}
		return searchBySQL(queryCountString.toString(), queryString.toString(), filterMap);
	}

	
	public String getEquipmentPath(String id,String fileName){
		try {
			Query query = getSession().createSQLQuery("select "+fileName+" from RQUIPMENT_MANAGE where id='"+id+"'");
			List list = query.list();
			String path = "";
			if (list.get(0)!=null){
				path = list.get(0).toString();
			}
			else{
				path = "nophoto.jpg";
			}
			return path;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	
	public String getEuipmentData(String id) {
		try {
			Query query = getSession().createSQLQuery("select equipmentdata from RQUIPMENT_MANAGE where id='"+id+"'");
			List list = query.list();
			String path = "";
			if (list.get(0)!=null){
				path = list.get(0).toString();
			}
			else{
				path = "";
			}
			return path;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	
	public String getEuipmentTask(String id) {
		try {
			String strSql = "select t2.id,t2.flow_name from rquipment_manage t1 left join flow_task t2 on t1.equipmenttaskno=t2.id where t1.id='"+id+"'";
			Query query = getSession().createSQLQuery(strSql);
			List list = query.list();
			String returnValue = "";
			if (list.get(0)!=null){
				Object[] datas = (Object[])list.get(0);
				if (datas[0]!=null && datas[1]!=null){
					returnValue = datas[0].toString()+",流程："+datas[1].toString();
					return returnValue;
				}
			}
			return "";
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	
	public String showEuipmentpersonPic(String id) {
		try {
			Query query = getSession().createSQLQuery("select t2.userid,t2.img_address from rquipment_manage t1 left join sys_users t2 on t1.equipmentperson=t2.userid where t1.id='"+id+"'");
			List list = query.list();
			String returnValue = "";
			if (list.get(0)!=null){
				Object[] datas = (Object[])list.get(0);
				if (datas[0]!=null && datas[1]!=null){
					returnValue = datas[0].toString()+","+datas[1].toString();
					return returnValue;
				}
			}
			return "";
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	
	public List getFloor1() {
		String strSql = "select orb.id idd,orb.visualname numbers,orb.parentid  pid,orb.type from SYS_VISUALINFO orb  where orb.type=-1 or orb.type=0 or orb.type=-2";
		Query query = getSession().createSQLQuery(strSql);
		List list = query.list();
		return list;
	}

	
	public List getFloor2() {
		String strSql = "select orb.id idd,orb.visualname numbers,orb.parentid  pid,orb.type from SYS_VISUALINFO orb  where orb.type=1";
		Query query = getSession().createSQLQuery(strSql);
		List list = query.list();
		return list;
	}

	
	public List getFloor3() {
		String strSql = "select orb.id idd,orb.visualname numbers,orb.parentid  pid,orb.type from SYS_VISUALINFO orb  where orb.type=2";
		Query query = getSession().createSQLQuery(strSql);
		List list = query.list();
		return list;
	}
}
